package com.lonely.fx.list_view;

import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.scene.control.cell.ComboBoxListCell;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;

/**
 * @date: 2022-07-28 21:34
 * @author: ztkj-hzb
 * @description: 单元格基于 CheckBoxListCell 效果演示
 **/
public class ListViewWithCheckBoxListCellSettingMain extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {


        AnchorPane anchorPane = new AnchorPane();

        //创建ListView
        ListView<User> listView = new ListView<>();

        ObservableList<User> users = FXCollections.observableArrayList();
        users.add(new User().setName("A"));
        users.add(new User().setName("B"));
        users.add(new User().setName("C"));
        users.add(new User().setName("D"));
        users.add(new User().setName("E"));
        users.add(new User().setName("F"));


        listView.setItems(users);


        //设置展示效果 和提交设置
        listView.setEditable(true);
        listView.setCellFactory(CheckBoxListCell.forListView(new Callback<User, ObservableValue<Boolean>>() {

            /**
             * 返回一个boolean类型的值，通过该值，确定在当前行的checkbox是否选中
             *
             * @param param
             * @return
             */
            @Override
            public ObservableValue<Boolean> call(User param) {

                if (param.getName().equals("A")) {
                    return new SimpleBooleanProperty(true);
                }

                return new SimpleBooleanProperty(false);
            }


        }, new StringConverter<User>() {
            @Override
            public String toString(User object) {
                return object.getName();
            }

            @Override
            public User fromString(String string) {
                return null;
            }
        }));


        AnchorPane.setLeftAnchor(listView, 100.0);
        anchorPane.getChildren().addAll(listView);
        primaryStage.setScene(new Scene(anchorPane));
        primaryStage.setWidth(500);
        primaryStage.setHeight(500);
        primaryStage.show();

    }


    /**
     * 用户信息
     */
    private class User {
        private String name;

        public String getName() {
            return name;
        }

        public User setName(String name) {
            this.name = name;
            return this;
        }
    }
}
